import json
import re
import time
import timeit

import pandas as pd
import requests


# 行业数据
# https://stock.sina.com.cn/stock/api/openapi.php/TouziService.getCateRank?p=2&num=12&orderby=zl_
# sub&ordertype=desc&&callback=jQuery111205846819718407235_1533823974704

# https://touzi.sina.com.cn/public/data
class stockInfo:
    _tablename_ = 'stock_info'

    def __init__(self):
        # 大盘指数
        self.index_array = ['sh000001', 'sz399001', 'sh000300']
        self.sh000001 = {'Symbol': 'sh000001', 'Name': '上证指数'}
        self.sz399001 = {'Symbol': 'sz399001', 'Name': '深证成指'}
        self.sh000300 = {'Symbol': 'sh000300', 'Name': '沪深300'}
        self.columns = ['name', 'open', 'close', 'high',
                        'low', 'yesterdayClose', 'bidPrice', 'askPrice', 'quantity', 'money',
                        'buy1Volume', 'buy1Price', 'buy2Volume', 'buy2Price',
                        'buy3Volume', 'buy3Price', 'buy4Volume', 'buy4Price',
                        'buy5Volume', 'buy5Price', 'sell1Volume', 'sell1Price',
                        'sell2Volume', 'sell2Price', 'sell3Volume',
                        'sell3Price',
                        'sell4Volume', 'sell4Price', 'sell5Volume',
                        'sell5Price',
                        'date', 'time']

    def get_realtime_stock_info(self, codes):
        # 股票名字,
        # 今日开盘价,
        # 昨日收盘价,
        # 当前价格,
        # 今日最高价,
        # 今日最低价,
        # 竞买价，即“买一”报价；
        # 竞卖价，即“卖一”报价；
        # 成交的股票数，由于股票交易以一百股为基本单位，所以在使用时，通常把该值除以一百；
        # 成交金额，单位为“元”，为了一目了然，通常以“万元”为成交金额的单位，所以通常把该值除以一万；
        # “买一”申请4695股，即47手；
        # “买一”报价；
        # 买二申请股数
        # #“买二”报价；
        # 买三申请股数
        # #“买三”报价；
        # 买四申请股数
        # #“买四”报价；
        # 买五申请股数
        # #“买五”报价；
        # “卖一”申请4695股，即47手；
        # “卖一”报价；
        # 卖二申请股数
        # #“卖二”报价；
        # 卖三申请股数
        # #“卖三”报价；
        # 卖四申请股数
        # #“卖四”报价；
        # 卖五申请股数
        # #“卖五”报价；
        # 日期
        # 时间
        codes = 'sh600856,sz002160'

        url = 'http://hq.sinajs.cn/list=' + codes

        r = requests.get(url)
        data = r.content.decode('GBK')
        print(data)
        datas = data.split(';')
        print(datas[0])
        print(datas[1])

    def getData(self, codes):
        url = 'http://hq.sinajs.cn/list=' + codes
        r = requests.get(url)
        data = r.content.decode('GBK')
        datas = data.split(';')
        datas = datas[:len(datas) - 1]
        stock_list = []

        if (len(datas)):
            for stockIinfo in datas:
                stock_list.append(self.transfer_data(stockIinfo))
        df = pd.DataFrame(stock_list, columns=self.columns)
        return df

    def transfer_data(self, data):
        data = data.split(',')

        name = data[0]
        todayOpen = data[1]
        yesterdayClose = data[2]
        nowPrice = data[3]
        todayHigh = data[4]
        todayLow = data[5]
        bidPrice = data[6]
        askPrice = data[7]
        quantity = data[8]
        money = data[9]
        buy1Volume = data[10]
        buy1Price = data[11]
        buy2Volume = data[12]
        buy2Price = data[13]
        buy3Volume = data[14]
        buy3Price = data[15]
        buy4Volume = data[16]
        buy4Price = data[17]
        buy5Volume = data[18]
        buy5Price = data[19]
        sell1Volume = data[20]
        sell1Price = data[21]
        sell2Volume = data[22]
        sell2Price = data[23]
        sell3Volume = data[24]
        sell3Price = data[25]
        sell4Volume = data[26]
        sell4Price = data[27]
        sell5Volume = data[28]
        sell5Price = data[29]
        date = data[30]
        time = data[31]
        data = {'name': data[0], 'open': todayOpen, 'yesterdayClose': yesterdayClose, 'close': nowPrice,
                'high': todayHigh,
                'low': todayLow, 'bidPrice': bidPrice, 'askPrice': askPrice, 'quantity': quantity, 'money': money,
                'buy1Volume': buy1Volume, 'buy1Price': buy1Price, 'buy2Volume': buy2Volume, 'buy2Price': buy2Price,
                'buy3Volume': buy3Volume, 'buy3Price': buy3Price, 'buy4Volume': buy4Volume, 'buy4Price': buy4Price,
                'buy5Volume': buy5Volume, 'buy5Price': buy5Price, 'sell1Volume': sell1Volume, 'sell1Price': sell1Price,
                'sell2Volume': sell2Volume, 'sell2Price': sell2Price, 'sell3Volume': sell3Volume,
                'sell3Price': sell3Price,
                'sell4Volume': sell4Volume, 'sell4Price': sell4Price, 'sell5Volume': sell5Volume,
                'sell5Price': sell5Price,
                'date': date, 'time': time}

        return data

    def load_ten_percent_stock(self):
        print("开始下载所有的股票符号..." + "\n")

        start = timeit.default_timer()

        all_quotes = []

        all_quotes.append(self.sh000001)  # 将大盘添加到最前面
        all_quotes.append(self.sz399001)  # 将大盘添加到最前面
        all_quotes.append(self.sh000300)  # 将大盘添加到最前面
        ## all_quotes.append(self.sz399005) #中小板最前面
        ## all_quotes.append(self.sz399006) #创业板最前面
        try:
            # page=1&num=40&sort=changepercent&asc=0&node=hs_a&symbol=&_s_r_a=page
            r_params = {'page': 1, 'num': 100, 'sort': 'changepercent', 'asc': 0, 'node': 'hs_a', '_s_r_a': 'page'}
            all_quotes_url = 'http://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeData'
            r = requests.get(all_quotes_url, params=r_params)  # 根据网址下载所有的股票编号，这里使用的是新浪网址，有很多网址可以下载股票编号
            print("从  " + r.url + "  处下载所有的股票编号")
            data = r.content.decode('GBK')
            data = re.sub('ticktime:"(.*?)",', '', data)
            data = data.replace('{', '{"').replace(':', '":').replace(',', ',"').replace(',"{"', ',{"')
            data = json.loads(data)
            columns = ['symbol', 'code', 'name', 'trade', 'pricechange', 'changepercent', 'buy', \
                       'sell', 'settlement', 'open', 'high', 'low', 'volume', 'amount', 'turnoverratio']
            datas = []
            for j in range(len(data)):
                stock_info = {}
                # 股票符号
                stock_info['symbol'] = data[j]['symbol']
                # 代码
                stock_info['code'] = data[j]['code']
                # 名称
                stock_info['name'] = data[j]['name']
                # 最新价
                stock_info['trade'] = float(data[j]['trade'])
                # 涨跌额
                stock_info['pricechange'] = float(data[j]['pricechange'])
                # 涨跌幅度
                stock_info['changepercent'] = float(data[j]['changepercent'])
                # 买入
                stock_info['buy'] = float(data[j]['buy'])
                # 卖出
                stock_info['sell'] = float(data[j]['sell'])
                # 昨收
                stock_info['settlement'] = float(data[j]['settlement'])
                # 今开
                stock_info['open'] = float(data[j]['open'])
                # 最高
                stock_info['high'] = float(data[j]['high'])
                # 最低
                stock_info['low'] = float(data[j]['low'])
                # 量
                stock_info['volume'] = int(data[j]['volume'])
                # 成交额
                stock_info['amount'] = float(data[j]['amount'])
                # 换手
                stock_info['turnoverratio'] = float(data[j]['turnoverratio'])
                datas.append(stock_info)
            print("下载所有的股票编号完成... time cost: " + str(round(timeit.default_timer() - start)) + "s" + "\n")
            if (len(datas) > 0):
                df = pd.DataFrame(datas)
                df = df.ix[:, columns]
                return df
        except Exception as e:
            print("Error: 下载股票编号失败..." + "\n")
            print(e)


if __name__ == '__main__':
    stock = stockInfo()
    df_ten = stock.load_ten_percent_stock()
    sysmbol_array = list(df_ten.symbol)
    codes = str(sysmbol_array).replace('[', '').replace(']', '').replace('\', \'', ',').replace('\'', '')
    print(codes)
    while (True):
        data = stock.getData('sz002299')
        # stock_base_info = ts.get_stock_basics()
        print(data)
        time.sleep(3)
